<template>
  <div class="div-main">
    <el-form :inline="true" :model="exchangeCode" class="demo-form-inline">
      <el-form-item label="优惠券名称">
        <el-input v-model="exchangeCode.code" placeholder="请输入兑换码" style="width: 160px"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
            v-model="exchangeCode.status"
            placeholder="兑换码状态"
            style="width: 140px"
        >
          <el-option
              v-for="item in statusList"
              :key="item.status"
              :label="item.statusName"
              :value="item.status"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getExchangeCodeList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table  :data="exchangeCodeList" style="width: 100%">
      <el-table-column prop="code" label="兑换码" width="180" />
      <el-table-column prop="couponName" label="优惠券名称" width="140" />
      <el-table-column prop="userName" label="领取人名称" width="100" />
      <el-table-column prop="expiredDate" label="有效期" width="120" >
        <template v-slot="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" >
        <template v-slot="scope">
          <span :style="{ color: getStatusColor(scope.row.status) }">{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="120" />
      <el-table-column fixed="right" label="操作" width="260">
        <template #default="{row}">
          <el-button link type="primary" size="small" @click="dele(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="showPagination">
      <el-pagination :page-size="10" :page-count="totalPage" layout="prev, pager, next" :total="totalCount" @current-change="handlePageChange"/>
    </div>
  </div>
</template>
<script setup>

import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {DeleteCoupon, ListExchangeCode} from "@/api/market.js";

const totalCount = ref(0)
const totalPage = ref(0)
const pagerCount=ref(10);

const showPagination = ref(false);

const exchangeCodeList=ref([])

const exchangeCode=ref({
  code:'',
  status:''
});
getExchangeCodeList();
function getExchangeCodeList(){
  console.info('查询兑换码列表')
  ListExchangeCode(exchangeCode.value)
      .then(res => {
        if (res.data.code === 200000) {
          exchangeCodeList.value=res.data.data.data
          if (res.data.data.totalCount > 0) {
            showPagination.value = true;
            totalPage.value=res.data.data.totalPage;
            totalCount.value=res.data.data.totalCount;
          }
        }
      })
}

function handlePageChange(newPage){
  exchangeCode.value.pageNum=newPage
  ListExchangeCode(exchangeCode.value)
      .then(res => {
        if (res.data.code === 200000) {
          exchangeCodeList.value=res.data.data.data
          if (res.data.data.totalCount > 0) {
            showPagination.value = true;
            totalPage.value=res.data.data.totalPage;
            totalCount.value=res.data.data.totalCount;
          }
        } else {
          //错误提示框
          ElMessage({
            message: res.data.msg,
            type: 'warning'
          });
        }
      })
}


function dele(data){
  ElMessageBox.confirm(
      '是否确认删除',
      '提醒',{
        confirmButtonText:'确认',
        cancelButtonText:'取消',
        type:'warning'
      }
  ).then(()=>{
    DeleteCoupon(data)
        .then(res => {
          if (res.data.code == 200000) {
            // hide();
            ElMessage({
              type:'success',
              message:'删除成功'
            });
            resetCoupon();
            getCouponList();
          } else {
            //错误提示框
            ElMessage({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
  }).catch(()=>{
    // ElMessage({
    //   type:'info',
    //   message:'删除取消'
    // })
  })
}


const statusList= ref([{
  status:0,
  statusName:'未使用'
},{
  status:1,
  statusName:'使用中'
},{
  status:2,
  statusName:'已使用'
},{
  status:3,
  statusName:'已过期'
}])



function getStatusColor(statusValue) {
  const statusColorMap = {
    0: 'black',
    1: 'blue',
    2: 'green',
    3: 'red'
  };
  return statusColorMap[statusValue] || 'black';
}

function getStatusText(statusValue) {
  const getStatusText = {
    0: '未使用',
    1: '使用中',
    2: '已使用',
    3: '已过期'
  };
  return getStatusText[statusValue] ||  '状态未知';
}

// function statusFormatter(row, column, cellValue) {
//   console.info("--------")
//   if (cellValue === 0) {
//     return '未使用';
//   } else if (cellValue === 1) {
//     return '使用中';
//   } else if (cellValue === 2) {
//     return '已使用';
//   } else if (cellValue === 3) {
//     return '已过期';
//   } {
//     return '';
//   }
// }
function formatDate(dateString) {
  // 使用Date对象的parse方法来解析字符串为毫秒时间戳（某些浏览器可能不需要parse，直接用new Date()）
  const date = new Date(dateString);

  // 获取年、月、日，并进行格式化（月份和日需要补零）
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 注意：月份是从0开始的，所以需要+1
  const day = String(date.getDate()).padStart(2, '0');

  // 返回格式化后的日期字符串，你想要的形式是“YYYY-MM-DD”
  return `${year}-${month}-${day}`;
}
</script>